package com.zhihu.jjn.demoproject.config;

import com.alibaba.fastjson.JSONObject;
import com.zhihu.jjn.demoproject.entity.Response;
import com.zhihu.jjn.demoproject.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕获
 *
 * @author xuyaohui
 * @date 2018-9-18
 */
@Slf4j
@RestControllerAdvice
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class GlobalExceptionHandler {

    private JSONObject formatErrorMessage(Exception e, HttpServletRequest req) {
        String errorPosition = "";
        if (e.getStackTrace().length > 0) {
            StackTraceElement element = e.getStackTrace()[0];
            String fileName = element.getFileName() == null ? "未找到错误文件" : element.getFileName();
            int lineNumber = element.getLineNumber();
            errorPosition = fileName + ":" + lineNumber;
        }
        JSONObject errorObject = new JSONObject();
        errorObject.put("requestIp", IpUtil.getIpAddr(req));
        errorObject.put("errorLocation", errorPosition);
        if (log.isErrorEnabled()) {
            log.error("异常:{}", e.getMessage());
            log.error("详细信息:", e);
        }
        return errorObject;
    }

    @ExceptionHandler(value = Exception.class)
    public Response commonExceptionHandler(HttpServletRequest req, Exception e) {
        JSONObject jsonObject = formatErrorMessage(e, req);
        return Response.error(jsonObject);
    }
}
